<template>
  <div class="bibi-deal theme-bg">
    <!-- 币币交易上面部分 -->
    <div class="deal flex js-sp mb-24 deal_width">
      <!-- 左侧盘口实时成交数据 -->
      <div class="handicap quotebg radius-8">
        <div
          class="hand-tabbox mb-19 flex js-st align-center point text-bold quotet3 text-14 quoteline"
        >
          <div
            class="hand-tab"
            @click="exChange(1)"
            :class="{ 'tabactive text-bolder quotet2': activeEx === 1 }"
          >
            {{ $t("deal.handicap") }}
          </div>
          <!-- <div
            class="hand-tab"
            @click="exChange(2)"
            :class="{ 'tabactive text-bolder quotet2': activeEx === 2 }"
          >
            {{ $t("deal.realtime") }}
          </div> -->
        </div>
        <div class="flex js-sp family-d text-bolder text-10 quotet3 mb-11">
          <div class="w-80 text-left">
            <div>
              {{ $t("deal.sell") }}
            </div>
          </div>
          <div class="flex align-center js-sp flex-grow-1">
            <div class="flex-grow-1">
              {{ $t("exchange.price") }}
            </div>
            <div class="flex-grow-1 text-right">
              <div>{{ $t("deal.buy") }}</div>
            </div>
          </div>
        </div>
        <div>
          <!-- 盘口数据 -->
          <Handicap
            v-if="activeEx === 1"
            :nowprice="state.nowprice"
            :selllist="state.handCap.transactionSellList"
            :buylist="state.handCap.transactionBuyList"
          />
        </div>
      </div>
      <!-- k线中间行情 -->
      <div class="deal-center radius-8 quotebg">
        <!-- 当前交易对数据 -->
        <div class="p-center mb-30">
          <div class="trad-data flex js-sp align-center">
            <div class="flex js-st align-center">
              <div class="quotet1 text-bolder text-26 family-d">
                {{ gettrading?.currency_name }}/{{ gettrading?.legal_name }}
              </div>
              <div class="tradata-right">
                <div class="flex js-st header-ul align-center">
                  <div class="family-d first-price">
                    <div
                      class="text-18 mb-2 text-bolder"
                      :class="
                        state.nowData.increaseValue > 0
                          ? 'text-green'
                          : 'text-red'
                      "
                    >
                      {{
                        $currency(
                          decimalDigitsInputFilter(
                            state.nowData.nowPrice,
                            gettrading?.price_accuracy
                          )
                        )
                      }}
                    </div>
                    <div class="quotet3 text-10">
                      ≈{{
                        $currency(
                          decimalDigitsInputFilter(
                            state.nowData.nowPrice,
                            gettrading?.price_accuracy
                          )
                        )
                      }}
                    </div>
                  </div>
                  <div class="ml-40">
                    <div class="quotet3 text-10 mb-4">
                      {{ $t("deal.increase") }}
                    </div>
                    <div
                      class="text-14 family-d text-bolder"
                      :class="
                        state.nowData.increaseValue > 0
                          ? 'text-green'
                          : 'text-red'
                      "
                    >
                      {{ (state.nowData.increaseValue * 100).toFixed(2) }}%
                    </div>
                  </div>
                  <div class="ml-40">
                    <div class="quotet3 text-10 mb-4">
                      {{ $t("deal.highest") }}
                    </div>
                    <div class="color_1e text-14 family-d text-bolder">
                      {{
                        $currency(
                          decimalDigitsInputFilter(
                            state.nowData.highPrice,
                            gettrading?.price_accuracy
                          )
                        )
                      }}
                    </div>
                  </div>
                  <div class="ml-40">
                    <div class="quotet3 text-10 mb-4">
                      {{ $t("deal.lowest") }}
                    </div>
                    <div class="color_1e text-14 family-d text-bolder">
                      {{
                        $currency(
                          decimalDigitsInputFilter(
                            state.nowData.lowPrice,
                            gettrading?.price_accuracy
                          )
                        )
                      }}
                    </div>
                  </div>
                  <div class="ml-40">
                    <div class="quotet3 text-10 mb-4">
                      {{ $t("exchange.24HTransactionVolume") }}
                    </div>
                    <div class="color_1e text-14 family-d text-bolder">
                      {{
                        $currency(
                          decimalDigitsInputFilter(
                            state.nowData.transactionAmount,
                            0
                          )
                        )
                      }}{{ gettrading?.currency_name }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div>
              <el-switch
                v-model="state.themeType"
                active-color="#333333"
                inactive-color="#F8F8F8"
                :class="state.themeType ? 'active_img' : 'inactive_img'"
                @change="changeTheme"
              ></el-switch>
            </div>
          </div>
          <!-- k线行情 -->
          <div class="kline radius-8">
            <!-- <kline-charts :data="state.klineData"></kline-charts> -->
            <s-tradingview
              v-if="$store.state.exchange.deal_data.id"
              :klineData="state.klineData"
              :is_MACD="false"
              :pageType="1"
              :decimal="Math.pow(10, gettrading?.price_accuracy)"
              class="tradingviewView"
            />
          </div>
        </div>
        <!-- 买入卖出交易 -->
        <Transaction
          @refreshParent="refreshChild"
          :nowprice="state.nowData.nowPrice"
          :isRoke="state.isRoke"
          @changeRoke="changeRoke"
        />
      </div>
      <!-- 交易对 -->
      <div class="deal-box flex-column quotebg">
        <div class="flex-shrink-0 mb-26">
          <Dealtrading @tradingNowData="tradingNowData" ref="Dealtrading" />
        </div>
        <!-- 实时数据 -->
        <div class="flex align-center js-st p_10">
          <div class="hand-tab activetab text-bolder quotet2 mb-16 w-65 P">
            {{ $t("deal.realtime") }}
          </div>
        </div>
        <div class="flex-grow-1 p_10 ">
          <div>
            <ul class="flex js-sp family-d text-bolder text-10 quotet3 p_10">
              <li>
                <div>{{ $t("exchange.price") }}</div>
                <div>(USDT)</div>
              </li>
              <li class="text-center">
                <div>
                  {{ $t("deal.volume") }}
                </div>
                <div>({{ gettrading?.currency_name }})</div>
              </li>
              <li class="w-50">
                <div>
                  {{ $t("assets.time") }}
                </div>
              </li>
            </ul>
            <Realtime
              :deallist="state.handCap?.transactionDealList || []"
              :time="state.handCap.time"
            />
          </div>
        </div>
      </div>
    </div>
    <!-- 下面表格 -->
    <div class="data-table quotebg radius-8 deal_width">
      <div
        class="table-tabbox flex js-st align-center point text-bold quotet3 text-14 quoteline"
      >
        <div
          class="table-tab"
          @click="changeTable(1)"
          :class="{ 'tabactive text-bolder quotet2': acTable === 1 }"
        >
          {{ $t("global.currentCommission") }}[{{ state.curentNum }}]
        </div>
        <div
          class="table-tab"
          @click="changeTable(2)"
          :class="{ 'tabactive text-bolder quotet2': acTable === 2 }"
        >
          {{ $t("global.historyCommission") }}
        </div>
      </div>
      <div class="table-block">
        <!-- 当前委托 -->
        <Curentcommin
          ref="curentCom"
          v-show="acTable === 1"
          @curenttotal="curentTotal"
          @changeRoke="changeRoke"
        />
        <!-- 历史委托 -->
        <Historycommin ref="hisCom" v-show="acTable === 2" />
      </div>
    </div>
  </div>
</template>

<script>
import {
  computed,
  onMounted,
  reactive,
  ref,
  getCurrentInstance,
  onBeforeUnmount,
  watch,
} from "vue";
import Dealtrading from "@/components/transaction/trading.vue";
import Transaction from "@/components/transaction/transaction.vue";
import Handicap from "@/components/transaction/handicap.vue";
import Realtime from "@/components/transaction/realtime.vue";
import Curentcommin from "@/components/transaction/curentcommin.vue";
import Historycommin from "@/components/transaction/historycommin.vue";
import { useStore } from "vuex";
import sTradingview from "@/components/sTradingview/sTradingview.vue";
import { decimalDigitsInputFilter, numSort } from "@/utils/common";
import { transactionRobotQuotation } from "@/api/currency";
import UseSystemSetting from "@/commonapi/useSystemSetting";

export default {
  components: {
    Dealtrading,
    Transaction,
    Handicap,
    Realtime,
    Curentcommin,
    Historycommin,
    // Websocket,
    sTradingview,
  },
  setup() {
    const $store = useStore();
    const state = reactive({
      timer: null,
      klineData: null,
      ordertype: "",
      iskline: false,
      handCap: {
        transactionSellList: [{ price: 0 }],
        transactionBuyList: [{ price: 0 }],
        transactionDealList: [{ price: 0 }],
      }, //盘口 实时成交数据
      nowData: {}, //当前时间数据
      nowprice: 0, //当前价
      curentNum: 0, //当前委托数据量
      themeType: true,
      isRoke: false, //是否撤单
    });
    const themeStyle = process.env.VUE_APP_COLOR; // dark初始色调
    const curentCom = ref(null);
    const hisCom = ref(null);
    const {
      appContext: {
        app: {
          config: { globalProperties },
        },
      },
    } = getCurrentInstance();
    const { $websocketTool } = globalProperties;
    // 获取开关状态
    const { virtual_wallet } = UseSystemSetting();
    const gettrading = computed(() => {
      return $store.state.exchange.deal_data;
    });
    watch(gettrading, (newData, oldData) => {
      closeMsg({
        socket_type:
          (virtual_wallet.value ? "DEMO_" : "") + "TRANSACTION_" + oldData?.id,
        subscribed: 0,
      });
      closeMsg({
        socket_type: oldData?.currency_name + "/" + oldData?.legal_name,
        subscribed: 0,
      });
      getData(newData?.id);
      if ($websocketTool?.ws && $websocketTool?.ws?.readyState == 1) {
        $websocketTool?.ws.send(
          JSON.stringify({
            socket_type:
              (virtual_wallet.value ? "DEMO_" : "") +
              "TRANSACTION_" +
              newData?.id,
            subscribed: 1,
          })
        );
        $websocketTool?.ws.send(
          JSON.stringify({
            socket_type: newData?.currency_name + "/" + newData?.legal_name,
            subscribed: 1,
          })
        );
      }
      if ($websocketTool?.ws && $websocketTool?.ws?.readyState == 1) {
        $websocketTool?.ws.send(
          JSON.stringify({
            socket_type:
              (virtual_wallet.value ? "DEMO_" : "") +
              "TRANSACTION_" +
              newData?.id,
            subscribed: 1,
          })
        );
        $websocketTool?.ws.send(
          JSON.stringify({
            socket_type: newData?.currency_name + "/" + newData?.legal_name,
            subscribed: 1,
          })
        );
      }
    });
    watch(
      () => $store.state.exchange.theme,
      (val) => {
        if (val === "night") {
          document.getElementsByTagName("body")[0].className =
            "theme-style-dark mode-style-" + themeStyle;
        } else {
          document.getElementsByTagName("body")[0].className =
            "mode-style-" + themeStyle;
        }
      }
    );
    const getData = (id) => {
      transactionRobotQuotation(id).then((res) => {
        state.handCap.transactionBuyList = numSort(
          "desc",
          res.data.transaction_buy_list,
          "price"
        );
        state.handCap.transactionSellList = numSort(
          "desc",
          res.data.transaction_sell_list,
          "price"
        );
        state.handCap.transactionDealList =
          res.data.transaction_deal_list || [];
      });
    };
    const changeRoke = () => {
      state.isRoke = !state.isRoke;
    };
    const Dealtrading = ref(null);
    onMounted(() => {
      if ($store.state.user.userInfo) {
        state.ordertype =
          (virtual_wallet.value ? "DEMO_" : "") +
          "USER_TRANSACTION_" +
          $store.state.user.userInfo.id;
      }
      //初始化样式
      state.themeType = $store.state.exchange.theme === "night" ? true : false;
      if ($store.state.exchange.theme === "night") {
        document.getElementsByTagName("body")[0].className =
          "theme-style-dark mode-style-" + themeStyle;
      } else {
        document.getElementsByTagName("body")[0].className =
          "mode-style-" + themeStyle;
      }

      state.timer = setInterval(() => {
        if ($websocketTool?.ws && $websocketTool?.ws?.readyState == 1) {
          clearInterval(state.timer);
          state.timer = null;
          handleMsg();
        }
      }, 3000);
      document.addEventListener("visibilitychange", visibilityFn);
    });
    const visibilityFn = () => {
      // 用户息屏、或者切到后台运行 （离开页面）
      if (document.visibilityState === "hidden") {
        // closeWsMessage();
        console.log("hidden");
      }
      // 用户打开或回到页面
      console.log(document.visibilityState);
      if (document.visibilityState === "visible") {
        if ($websocketTool?.ws && $websocketTool?.ws?.readyState == 1) {
          handleMsg();
        }
      }
    };
    const handleMsg = () => {
      getData(gettrading.value?.id);
      $websocketTool?.ws.send(
        JSON.stringify({
          socket_type:
            (virtual_wallet.value ? "DEMO_" : "") +
            "TRANSACTION_" +
            gettrading.value?.id,
          subscribed: 1,
        })
      );
      $websocketTool?.ws.send(
        JSON.stringify({
          socket_type:
            gettrading.value?.currency_name +
            "/" +
            gettrading.value?.legal_name,
          subscribed: 1,
        })
      );
      if (state.ordertype) {
        $websocketTool?.ws.send(
          JSON.stringify({
            socket_type: state.ordertype,
            subscribed: 1,
          })
        );
      }
      $websocketTool.ws.onmessage = function(res) {
        const message = JSON.parse(res.data);
        if (
          message.type ===
          (virtual_wallet.value ? "DEMO_" : "") +
            "TRANSACTION_" +
            gettrading.value?.id
        ) {
          if (message) {
            onMessage(message);
          }
        }
        if (message.type === "RANKING") {
          if (Dealtrading.value) {
            Dealtrading.value.onMessageTrading(message);
          }
        }
        if (
          message.type ===
          gettrading.value?.currency_name + "/" + gettrading.value?.legal_name
        ) {
          klineChange(message);
        }
        if (state.ordertype) {
          if (message.type === state.ordertype) {
            orderChange();
          }
        }
      };
    };
    const closeMsg = (msg) => {
      if ($websocketTool?.ws && $websocketTool.ws.readyState == 1) {
        $websocketTool?.ws.send(JSON.stringify(msg));
      }
    };

    // websocket订单状态变更
    const orderChange = () => {
      refreshChild();
    };
    // 获取websocket盘口数据
    const onMessage = (val) => {
      state.handCap = val;
    };
    // 首次进来的当前数据先用交易对
    const tradingNowData = (val) => {
      if (val) {
        state.nowData = val;
        state.nowprice = val.nowPrice;
      }
    };
    const changeTheme = (val) => {
      state.themeType = val;
      if (val) {
        $store.commit("exchange/SET_THEME", "night");
      } else {
        $store.commit("exchange/SET_THEME", "day");
      }
    };
    const klineChange = (val) => {
      state.nowData = val.increaseData;
      state.nowprice = val.increaseData.nowPrice;
      state.klineData = val;
    };
    const activeEx = ref(1);
    const acTable = ref(1);
    const exChange = (i) => {
      activeEx.value = i;
    };
    const changeTable = (i) => {
      acTable.value = i;
    };
    // 获取当前委托数据量
    const curentTotal = (val) => {
      state.curentNum = val;
    };
    const refreshChild = () => {
      setTimeout(() => {
        curentCom.value.refresh();
        hisCom.value.refresh();
      }, 100);
    };
    const closeWsMessage = () => {
      if (state.timer) {
        clearInterval(state.timer);
        state.timer = null;
      }
      closeMsg({
        socket_type:
          (virtual_wallet.value ? "DEMO_" : "") +
          "TRANSACTION_" +
          gettrading.value.id,
        subscribed: 0,
      });
      closeMsg({
        socket_type:
          gettrading.value.currency_name + "/" + gettrading.value.legal_name,
        subscribed: 0,
      });
      closeMsg({
        socket_type: state.ordertype,
        subscribed: 0,
      });
      $store.commit("exchange/SET_REDIRECT_URL", "");
    };
    onBeforeUnmount(() => {
      document.removeEventListener("visibilitychange", visibilityFn);
      closeWsMessage();
    });
    return {
      state,
      exChange,
      changeTable,
      activeEx,
      acTable,
      gettrading,
      onMessage,
      klineChange,
      tradingNowData,
      orderChange,
      curentTotal,
      decimalDigitsInputFilter,
      handleMsg,
      closeMsg,
      Dealtrading,
      curentCom,
      hisCom,
      refreshChild,
      changeTheme,
      themeStyle,
      getData,
      changeRoke,
      closeWsMessage,
      visibilityFn,
    };
  },
};
</script>
<style scoped lang="less">
.w-65 {
  // min-width: 65px;
  display: inline-block;
}
.w-80 {
  width: 80px;
}
.mb-26 {
  margin-bottom: 26px;
}
.mb-16 {
  margin-bottom: 16px;
}
.bibi-deal {
  padding: 20px 0;
  box-sizing: border-box;
  padding-bottom: 60px;
}
.w-80 {
  width: 80px;
}
.deal {
  // width: 77.77%;
  margin: 0 auto;
}
.deal-box {
  min-width: 16.7%;
  max-height: 840px;
}
.deal-center {
  width: 63.55%;
  min-height: 775px;
  padding-bottom: 20px;
  box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.1);
}
.p-center {
  padding: 0 16px;
  box-sizing: border-box;
}
.trad-data {
  height: 60px;
}
.tradata-right {
  // width: 580px;
  padding-inline-end: 16px;
  margin-inline-start: 10px;
}
.p_10 {
  padding: 0 10px;
}
.mb-4 {
  margin-bottom: 4px;
}
.mb-2 {
  margin-bottom: 2px;
}
.mb-30 {
  margin-bottom: 30px;
}
.mb-24 {
  margin-bottom: 24px;
}
.mb-11 {
  margin-bottom: 11px;
}
.mb-19 {
  margin-bottom: 19px;
}
.ml-40 {
  margin-inline-start: 40px;
}
.kline {
  width: 100%;
  height: 385px;
}
.handicap {
  width: 17.85%;
  // height: 775px;
  padding: 10px;
  box-sizing: border-box;
  box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.1);
}
.hand-tab {
  min-height: 23px;
  margin-inline-end: 24px;
  position: relative;
  text-align: center;
  line-height: 24px;
}
.w-50 {
  width: 50px;
}
.data-table {
  // width: 77.77%;
  box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.1);
  margin: 0 auto;
}
.table-tabbox {
  padding: 10px 30px 0;
  // border-bottom: 1px solid;
}
.table-tab {
  padding: 2px 4px;
  line-height: 20px;
  position: relative;
  margin-inline-end: 30px;
}
.table-block {
  padding: 30px;
  box-sizing: border-box;
}
@media (min-width: 1301px) {
  .header-ul li {
    // min-width: 35%;
    text-align: start;
    margin-inline-end: 20px;
  }
}
@media (max-width: 1300px) {
  .header-ul li {
    // min-width: 28.5%;
    text-align: start;
    margin-inline-end: 10px;
  }
}
.first-price {
  min-width: 120px !important;
}
.active_img /deep/ .el-switch__core .el-switch__action {
  background-image: url("../../assets/images/night.png");
  background-repeat: no-repeat;
  background-size: 13px 13px;
  background-position: 1.5px 1px;
}
.inactive_img /deep/ .el-switch__core .el-switch__action {
  background-image: url("../../assets/images/day.png");
  background-repeat: no-repeat;
  background-size: 13px 13px;
  background-position: 1.5px 1px;
}
</style>
